package com.briup.pts.service.impl;

import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Hurdles;
import com.briup.pts.domain.vo.HurdlesVO;
import com.briup.pts.mapper.HurdlesMapper;
import com.briup.pts.service.HurdlesService;
import com.briup.pts.util.AssertUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@RequiredArgsConstructor
public class HurdlesServiceImpl implements HurdlesService {

    private final HurdlesMapper mapper;

    @Transactional
    @Override
    public void changeSaved(String hId, int changeNum) {
        // 根据id获取栏圈信息，判断其是否存在
        Hurdles hurdles = mapper.selectById(hId);
        AssertUtil.requiredNotNull(hurdles,
                ResultCode.HURDLES_IS_NOT_EXISTS);
        // 再而判断栏圈的状态是否可用，包括但不限于是否已满/为空等
        AssertUtil.isTrue("可用".equals(hurdles.getHEnable()),
                ResultCode.HURDLES_IS_NOT_ENABLE);
        // 判断栏舍是否已满
        int saved = hurdles.getHSaved() + changeNum;
        AssertUtil.isTrue(hurdles.getHMax() >= saved,
                ResultCode.HURDLES_IS_FULL);
        // 同时防止出现原本为0，还要减少数据的情况
        AssertUtil.isTrue(0 <= saved,
                ResultCode.HURDLES_IS_EMPTY);
        // 修改数量
        mapper.changeSaved(hId, saved,
                saved == hurdles.getHMax() ? "已满" : "未满");
    }

    @Override
    public List<HurdlesVO> queryAll() {
        // 查询所有的栏圈及其栏舍信息
        return mapper.queryAllWithFh();
    }
}